import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { STColumn, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFSchema } from '@delon/form';
import { FreightAccountService } from '../../../services/freight-account.service';

@Component({
  selector: 'app-withdrawals-detail',
  templateUrl: './withdrawals-detail.component.html',
  styleUrls: ['./withdrawals-detail.component.less']
})
export class WithdrawalsDetailComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: Component;
  @ViewChild('sf', { static: false })
  inputSF!: SFComponent;
  columns: STColumn[] = this.initST();
  inputSearchSchema: SFSchema = this.initInputSF();
  _$expand = false;

  formData: any = {};

  timeLineData: any = [];

  accountType = '1';

  constructor(public service: FreightAccountService, private route: ActivatedRoute) {
    const id = route.snapshot.params.id;
    this.accountType = route.snapshot.queryParams.type;
    this.loadRefundDetail(id);
  }

  ngOnInit(): void {}

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.inputSF?.value) {
      Object.assign(requestOptions.body, {
        ...this.inputSF.value
      });
    }
    Object.assign(requestOptions.body, { refundApplicationId: this.route.snapshot.params.id });
    return requestOptions;
  };

  loadRefundDetail(id: string) {
    this.service.request(this.service.$api_get_refund_detail, { id }).subscribe(res => {
      if (res) {
        this.formData = res;
        // 处理流程节点数据
        // 流程是否结束
        let isEnd = false;
        if (res.successTime) {
          isEnd = true;
          if (res.refundStatus === '3') {
            this.timeLineData.push({ time: res.successTime, value: `到账成功`, color: 'green' });
          } else {
            this.timeLineData.push({ time: res.successTime, value: `提现失败`, color: 'red' });
          }
        }
        if (res.agreeTime && res.refundStatus !== '4') {
          this.timeLineData.push({ time: res.agreeTime, value: `银行处理中`, color: 'gray' });
        }
        if (res.agreeTime) {
          if (res.refundStatus === '4') {
            isEnd = true;
            this.timeLineData.push({
              time: res.agreeTime,
              value: `拒绝提现<br/>操作人员：${res.handlerUserIdLabel}`,
              color: 'red'
            });
          } else {
            this.timeLineData.push({
              time: res.agreeTime,
              value: `审核通过<br/>操作人员：${res.handlerUserIdLabel}`,
              color: 'gray'
            });
          }
        }
        if (res.createTime) {
          this.timeLineData.push({
            time: res.createTime,
            value: `提交提现申请<br/>提现${res.amount}元至${res.bankName}(${res.bankCardNumber})<br/>操作人员：${res.userIdLabel}`,
            color: 'gray'
          });
        }
        if (this.timeLineData?.length > 0 && !isEnd) {
          this.timeLineData[0].color = 'green';
        }
      }
    });
  }

  downBack() {
    if (this.formData?.refundStatus !== '3') {
      return;
    }
    this.service.getReceiptUrl(this.formData.receiptUrl, {
      bankType: this.formData.bankType,
      rmYll: this.formData.userId,
      snglFlgCd: this.formData.coreSerNo,
      bussType: '06',
      ltdId: this.formData.ltdId,
      accountType: this.formData.accountType
    });
  }

  /**
   * 重置表单
   */
  resetInputSF() {
    this.inputSF.reset();
  }

  /**
   * 伸缩查询条件
   */
  expandToggle() {
    this._$expand = !this._$expand;
    this.inputSF?.setValue('/expand', this._$expand);
  }

  goBack() {
    history.go(-1);
  }

  // 导出
  exprot() {
    this.service.exportStart(
      { ...this.inputSF.value, pageSize: -1, refundApplicationId: this.route.snapshot.params.id },
      this.service.$api_export_refund_detail_page
    );
  }

  private initInputSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        orderPaymentCode: {
          type: 'string',
          title: '支付编号',
          ui: {
            placeholder: '请输入'
          }
        },
        billCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '请输入'
          }
        },
        resourceCode: {
          type: 'string',
          title: '货源编号',
          ui: {
            placeholder: '请输入'
          }
        },
        serviceType: {
          type: 'string',
          title: '服务类型',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'service:type' },
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        driverName: {
          type: 'string',
          title: '承运司机',
          ui: {
            placeholder: '请输入司机姓名/手机号',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        driverLicensePlate: {
          type: 'string',
          title: '车牌号',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        captain: {
          type: 'string',
          title: '收款人',
          ui: {
            placeholder: '请输入收款人姓名/手机号',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        isCaptain: {
          type: 'string',
          title: '车队长收款',
          enum: [
            {label: '全部', value: ''},
            {label: '是', value: '1'},
            {label: '否', value: '0'}
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '支付编号', index: 'orderPaymentCode', className: 'text-left', width: 200 },
      {
        title: '支付金额',
        index: 'payAmount',
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.payAmount }) },
        width: 140
      },
      { title: '运费明细', render: 'amountDetails', className: 'text-right', width: 150 },
      { title: '网络货运人', index: 'ltdName', className: 'text-left', width: 200 },
      { title: '货主', index: 'enterpriseInfoName', className: 'text-left', width: 200 },
      { title: '项目名称', index: 'enterpriseProjectName', className: 'text-left', width: 200 },
      { title: '订单号', render: 'billId', width: 200 },
      { title: '运单号', render: 'wayBillId', width: 200 },
      { title: '货源编号', index: 'resourceCode', width: 200 },
      {
        title: '服务类型',
        index: 'serviceType',
        className: 'text-center',
        width: 150,
        type: 'enum',
        enum: { '1': '抢单', '2': '指派', '3': '二维码', '4': '手工单' }
      },
      { title: '承运司机', render: 'driverId', width: 150 },
      { title: '收款人', render: 'captainName', className: 'text-left', width: 150 },
      { title: '银行类型', index: 'bankTypeLabel', className: 'text-center', width: 150 }
    ];
  }
}
